package com.example.joblinker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.dto.ChatMessageDTO;
import com.example.joblinker.entity.ChatMessage;
import com.example.joblinker.entity.Job;
import com.example.joblinker.entity.User;
import com.example.joblinker.mapper.ChatMessageMapper;
import com.example.joblinker.mapper.JobMapper;
import com.example.joblinker.mapper.UserMapper;
import com.example.joblinker.service.ChatMessageService;
import com.example.joblinker.vo.ChatMessageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 聊天消息服务实现类
 */
@Service
public class ChatMessageServiceImpl implements ChatMessageService {
    
    @Resource
    private ChatMessageMapper chatMessageMapper;
    
    @Resource
    private UserMapper userMapper;
    
    @Resource
    private JobMapper jobMapper;
    
    @Override
    public Page<ChatMessageVO> getJobChatMessages(Long jobId, Long userId, Integer page, Integer size) {
        // 1. 检查职位是否存在
        Job job = jobMapper.selectById(jobId);
        if (job == null) {
            throw new RuntimeException("职位不存在");
        }
        
        // 2. 构建查询条件，获取与当前用户相关的聊天记录
        // (userId是发送者或接收者) AND (jobId = ?)
        LambdaQueryWrapper<ChatMessage> wrapper = new LambdaQueryWrapper<ChatMessage>()
                .eq(ChatMessage::getJobId, jobId)
                .and(w -> w.eq(ChatMessage::getSenderId, userId)
                        .or()
                        .eq(ChatMessage::getReceiverId, userId))
                .orderByAsc(ChatMessage::getCreateTime);
        
        // 3. 分页查询
        Page<ChatMessage> messagePage = new Page<>(page, size);
        Page<ChatMessage> messageResult = chatMessageMapper.selectPage(messagePage, wrapper);
        
        // 4. 转换结果
        List<Long> userIds = new ArrayList<>();
        for (ChatMessage message : messageResult.getRecords()) {
            userIds.add(message.getSenderId());
            userIds.add(message.getReceiverId());
        }
        
        // 5. 批量查询用户信息
        Map<Long, User> userMap = new HashMap<>();
        if (!userIds.isEmpty()) {
            List<User> users = userMapper.selectBatchIds(userIds);
            userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));
        }
        
        // 6. 构建VO
        List<ChatMessageVO> voList = new ArrayList<>();
        for (ChatMessage message : messageResult.getRecords()) {
            ChatMessageVO vo = new ChatMessageVO();
            BeanUtils.copyProperties(message, vo);
            
            // 设置发送者姓名
            User sender = userMap.get(message.getSenderId());
            if (sender != null) {
                vo.setSenderName(sender.getUsername());
            }
            
            // 设置接收者姓名
            User receiver = userMap.get(message.getReceiverId());
            if (receiver != null) {
                vo.setReceiverName(receiver.getUsername());
            }
            
            voList.add(vo);
        }
        
        // 7. 构建结果页
        Page<ChatMessageVO> voPage = new Page<>(messageResult.getCurrent(), messageResult.getSize(), messageResult.getTotal());
        voPage.setRecords(voList);
        
        return voPage;
    }
    
    @Override
    public ChatMessageVO sendJobChatMessage(Long jobId, Long senderId, ChatMessageDTO messageDTO) {
        // 1. 检查职位是否存在
        Job job = jobMapper.selectById(jobId);
        if (job == null) {
            throw new RuntimeException("职位不存在");
        }
        
        // 2. 检查发送者和接收者是否存在
        User sender = userMapper.selectById(senderId);
        User receiver = userMapper.selectById(messageDTO.getReceiverId());
        if (sender == null || receiver == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 3. 创建消息实体
        ChatMessage message = new ChatMessage();
        message.setJobId(jobId);
        message.setSenderId(senderId);
        message.setReceiverId(messageDTO.getReceiverId());
        message.setContent(messageDTO.getContent());
        message.setIsRead(0); // 未读
        message.setCreateTime(LocalDateTime.now());
        message.setUpdateTime(LocalDateTime.now());
        
        // 4. 保存消息
        chatMessageMapper.insert(message);
        
        // 5. 构建返回VO
        ChatMessageVO vo = new ChatMessageVO();
        BeanUtils.copyProperties(message, vo);
        vo.setSenderName(sender.getUsername());
        vo.setReceiverName(receiver.getUsername());
        
        return vo;
    }
} 